/**
 * 　　　　　　　　┏┓　　　┏┓
 * 　　　　　　　┏┛┻━━━┛┻┓
 * 　　　　　　　┃　　　　　　　┃
 * 　　　　　　　┃　　　━　　　┃
 * 　　　　　　　┃　＞　　　＜　┃
 * 　　　　　　　┃　　　　　　　┃
 * 　　　　　　　┃...　⌒　...　┃
 * 　　　　　　　┃　　　　　　　┃
 * 　　　　　　　┗━┓　　　┏━┛
 * 　　　　　　　　　┃　　　┃　Code is far away from bug with the animal protecting
 * 　　　　　　　　　┃　　　┃   神兽保佑,代码无bug
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┃
 * 　　　　　　　　　┃　　　┗━━━┓
 * 　　　　　　　　　┃　　　　　　　┣┓
 * 　　　　　　　　　┃　　　　　　　┏┛
 * 　　　　　　　　　┗┓┓┏━┳┓┏┛
 * 　　　　　　　　　　┃┫┫　┃┫┫
 * 　　　　　　　　　　┗┻┛　┗┻┛
 */

#import "PywSdk.h"
#import "PywAppInfo.h"
#import "PywPlatformMain.h"
#import "PywFloatView.h"
#import "UIImage+Pyw.h"
#import "AIFInitManager.h"
#import "PropertyListReformer.h"
#import "ApiClientConst.h"
#import "PywUser.h"
#import "PywIQKeyboardManager.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywSdk+login.h"
#import "PywCommonManager.h"
#import "PywInitApi.h"
#import "PywSplashView.h"
#import "PywUploadAccountLoginManager.h"
#import "PywBuriedManager.h"

#import "PywFastRegisterApi.h"
#import "PywRSAUtil.h"
#import "PywPassportUtils.h"
#import "PywRealNameAuthManager.h"
#import "LocalInfoUtil.h"

@implementation PywInitConfigure
@synthesize gamekey;
@synthesize canHideLogin;

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.canHideLogin = YES;
    }
    return self;
}

@end

static PywSdk *_instance;
@interface PywSdk()
@property (nonatomic, strong) PywInitApi *mInitApi;
@property (nonatomic, strong) PywSplashView *splashImageView;
@property (nonatomic, strong) PywFastRegisterApi *fastRegisterApi;
@property (nonatomic, assign) BOOL isSplash;
@end
@implementation PywSdk
// 定时器
NSTimer *lookforTimer;

+ (PywSdk *)manger
{
    static id manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[PywSdk alloc] init];
    });
    return manger;
}

- (instancetype)init
{
    if (self) {
        self = [super init];
    }
    return self;
}

#pragma mark - getter
- (PywSplashView *)splashImageView
{
    if (!_splashImageView) {
        _splashImageView = [[PywSplashView alloc] init];
    }
    return _splashImageView;
}
- (PywInitApi *)mInitApi
{
    if (!_mInitApi) {
        _mInitApi = [PywInitApi manager];
    }
    return _mInitApi;
}

- (PywFastRegisterApi *)fastRegisterApi{
    if (!_fastRegisterApi) {
        _fastRegisterApi = [PywFastRegisterApi manager];
    }
    return _fastRegisterApi;
}

/**
 *  初始化SDK
 *
 *  @param configure 配置信息
 *  @param isSplash  是否配置闪屏，YES：有闪屏，NO：无闪屏
 */
- (void)initialize:(PywInitConfigure *)configure
          isSplash:(BOOL)isSplash
{
    self.isSplash = isSplash;
    // 统一UI属性设置
    [self configreAppearance];
    // 保存appid、appkey、appScheme
    [PywAppInfo sharedAppInfo].gameKey = configure.gamekey;
    [PywAppInfo sharedAppInfo].sdk_api_url = configure.sdk_api_url;
    [PywAppInfo sharedAppInfo].sdk_pay_url = configure.sdk_pay_url;
    [PywAppInfo sharedAppInfo].th_ch_id = configure.th_ch_id;
    [PywPlatformMain sharedPlatformMain].canHideLogin = configure.canHideLogin;
    AppType atype = [self changeToAppType:configure.pyw_sdk_type];
    // 配置初始化SDK环境
    [self configureInitSDKEnvironmentWithAppType:atype];
    
    // 闪屏配置
    if (self.isSplash) {
        [self showSplashImgView];
    }
}

-(AppType) changeToAppType:(int) i{
    if(i == 7){
        return APPTypeBOTAH;
    }else if(i == 6){
        return AppTypeFQ;
    }
    return AppTypePYW;
}

- (void)configureInitSDKEnvironmentWithAppType:(AppType)appType{
    // 初始化注销状态
    [PywPlatformMain sharedPlatformMain].logouted = NO;
    [PywPlatformMain sharedPlatformMain].initialized = NO;
    
    [PywAppInfo sharedAppInfo].seriviceType = kAIFServicePro;
    
    [[PywCommonManager manager] changeWebViewUserAgnet];
    
    [PywAppInfo sharedAppInfo].appType = appType;
    
    [self reachabilityStartMonitoring];
}

- (void)didEnterBackgroundOrExitApplication
{
    //开启后台任务
    [self applicationBackgrounTaskTime];
    
    [[PywUploadAccountLoginManager manager] saveAccountLoginEndTime];
    [[PywBuriedManager manager] uploadUserActionData];
}

/// 开启后台任务
- (void)applicationBackgrounTaskTime
{
    UIApplication *app = [UIApplication sharedApplication];
    __block   UIBackgroundTaskIdentifier bgTask;
    //开启一个后台任务
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        //结束指定的任务（不管有没有完成，结束bgTask任务）
        [app endBackgroundTask:bgTask];
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid){
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    // 添加定时器
    [self addTimer];
}
#pragma mark - Other
/// 自动注册并登录
- (void)usedAutoRegisterAndLogin
{
    WEAK_SELF;
    [self.fastRegisterApi requestFastRegisterWithFlag:FastRegisterFlag_Register success:^(NSString *status, id anyObjct) {
        
        NSString *account = [NSString stringWithFormat:@"%@",anyObjct[@"account"]];
        NSString *password = [NSString stringWithFormat:@"%@",anyObjct[@"password"]];
        PLog(@"account = %@     password = %@",account,password);
        
        STRONG_SELF(weakSelf);
        [strongSelf fastAutoLoginWithAccount:account password:password];
    } fail:^(NSError *error) {
        PLog(@"自动注册失败！");
    }];
}
- (void)fastAutoLoginWithAccount:(NSString *)account password:(NSString *)password
{
    WEAK_SELF;
    [self.fastRegisterApi requestFastRegisterLoginWithFlag:FastRegisterFlag_Login
                                                   account:account
                                                  password:password
                                                   success:^(NSString *status, id anyObjct) {
                                                       // 保存数据后，发送通知
                                                       STRONG_SELF(weakSelf);
                                                       [strongSelf saveDataInfoWithDict:anyObjct
                                                                                account:account
                                                                               password:password];
                                                       
                                                   } fail:^(NSError *error) {
                                                       PLog(@"自动登录失败！");
                                                   }];
}
/**
 *  保存数据信息
 *
 *  @param dict <#dict description#>
 */
- (void)saveDataInfoWithDict:(NSDictionary *)dict account:(NSString *)account password:(NSString *)password
{
    // 保存返回数据
    [PywPlatformMain sharedPlatformMain].uid = [NSString stringWithFormat:@"%@",dict[@"cp_uid"]];
    [PywPlatformMain sharedPlatformMain].token = [NSString stringWithFormat:@"%@",dict[@"token"]];
    
    // 保存用户模型
    PywUser *user = [[PywUser alloc] init];
    user.passport = account;
    user.password = [PywRSAUtil encryptString:password];
    [PywPassportUtils savePassport:user];
    
    [PywPlatformMain sharedPlatformMain].accountType = UserType_Account;
    [PywPlatformMain sharedPlatformMain].userName = user.passport;
    [PywPlatformMain sharedPlatformMain].account = user.passport;
    [PywPlatformMain sharedPlatformMain].account_pwd = user.password;
    
    // 保存登录的状态
    [PywPlatformMain sharedPlatformMain].logined = YES;
    [PywPlatformMain sharedPlatformMain].logouted = NO;
    [PywPlatformMain sharedPlatformMain].is_game_fast_login = YES;
    
    /**
     *  发送“登录成功”通知
     */
    NSMutableDictionary *mDict = [[NSMutableDictionary alloc] init];
    [mDict setObject:[NSNumber numberWithInt:PYW_LOGIN_STATE_SUCCESS] forKey:@"result"];
    [mDict setObject:@"登录成功" forKey:@"info"];
    [mDict setObject:[PywPlatformMain sharedPlatformMain].account forKey:@"account"];
    [[NSNotificationCenter defaultCenter] postNotificationName:kPywCPLoginNotification object:nil userInfo:mDict];
    
    // Modal出“实名认证”控制器，加载Web端实名制认证
    [[PywRealNameAuthManager manager] showRealNameAuthViewController];
}

#pragma mark - 添加定时器
- (void)addTimer
{
    NSLog(@"添加定时器");
    lookforTimer = [NSTimer scheduledTimerWithTimeInterval:60.0
                                                    target:self
                                                  selector:@selector(lookforCard:)
                                                  userInfo:nil
                                                   repeats:NO];
    [[NSRunLoop mainRunLoop] addTimer:lookforTimer
                              forMode:NSRunLoopCommonModes];
}
- (void)lookforCard:(NSTimer *)timer
{
    //执行事件
    NSLog(@"定时时间到--Home键切换到后台，超过1分钟，记录一次“退出页面”。页面编码: %@ ",[PywBuriedManager manager].page_sn);
    if ([PywBuriedManager manager].page_sn.length > 0) {
        [[PywBuriedManager manager] saveUserActionDataWithPageSn:[PywBuriedManager manager].page_sn actionSn:@"2" typeSn:@"2"];
        NSLog(@"页面%@退出",[PywBuriedManager manager].page_sn);
    }
}
#pragma mark - 移除定时器
- (void)removeTimer
{
    NSLog(@"移除定时器");
    [lookforTimer invalidate];
    lookforTimer = nil;
}

- (void)didWillEnterForeground
{
    // 移除定时器
    [self removeTimer];
    
    [[PywUploadAccountLoginManager manager] uploadAccountLoginTimeLong];
}

#pragma mark - Actions
/**
 *  初始化 request
 */
- (void)requestInitData
{
    WEAK_SELF;
    [self.mInitApi requestInitWithSuccess:^(NSString *status, id anyObjct) {
        [[PywBuriedManager manager] uploadUserActionData];
        [weakSelf performSelector:@selector(delayRemoveSplashView)
                       withObject:nil afterDelay:1.f];
    } fail:^(NSError *error) {
        [weakSelf performSelector:@selector(delayRemoveSplashView)
                       withObject:nil afterDelay:1.f];
    }];
}

- (void)reachabilityStartMonitoring
{
    /**
     *  判断网络状态再去请求初始化（适配iOS10国行设备的访问网络权限）
     */
    WEAK_SELF;
    [[ApiClient sharedApiClient] reachabilityStartMonitoringAndStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        if (![PywPlatformMain sharedPlatformMain].initialized) {
            [weakSelf requestInitData];
        }
    }];
}

/**
 *  移除闪屏
 */
- (void)delayRemoveSplashView
{
    if (self.isSplash) {
        [self.splashImageView removeFromSuperview];
    }
    
    // 读取无缓存账号,且同时开启“手机注册”、“快速注册”和“自动注册并登录”开关
    // wtf!!!!
//    if ([PywAppInfo sharedAppInfo].game_cache_account.count == 0
//        && [PywPlatformMain sharedPlatformMain].is_autoRegisterLogin == YES
//        && [PywPlatformMain sharedPlatformMain].is_fastRegister == YES
//        && [PywPlatformMain sharedPlatformMain].is_reg_open == YES) {
    
    BOOL ret = YES;
    NSString * url = [PywAppInfo sharedAppInfo].notice_url;
    if(url && url.length){
        int32_t msgid = [[self getParamValueFromUrl:url paramName:@"id"] intValue];
        ret = [LocalInfoUtil getMsgStatus:msgid];
    }
    
    if (ret && [PywAppInfo sharedAppInfo].game_cache_account.count == 0
        && [PywPlatformMain sharedPlatformMain].is_autoRegisterLogin
        && [PywPlatformMain sharedPlatformMain].is_fastRegister
        && [PywPlatformMain sharedPlatformMain].is_reg_open) {
        PLog(@"自动注册并登录游戏！");
        [self usedAutoRegisterAndLogin];
    }
}

//从url中截取参数
-(NSString *) getParamValueFromUrl:(NSString *)url paramName:(NSString *)paramName{
    if (![paramName hasSuffix:@"="]) {
        paramName = [NSString stringWithFormat:@"%@=", paramName];
    }
    
    NSString *str = nil;
    NSRange   start = [url rangeOfString:paramName];
    if (start.location != NSNotFound) {
        // confirm that the parameter is not a partial name match
        unichar  c = '?';
        if (start.location != 0) {
            c = [url characterAtIndex:start.location - 1];
        }
        if (c == '?' || c == '&' || c == '#') {
            NSRange     end = [[url substringFromIndex:start.location + start.length] rangeOfString:@"&"];
            NSUInteger  offset = start.location + start.length;
            str = end.location == NSNotFound ?
            [url substringFromIndex:offset] :
            [url substringWithRange:NSMakeRange(offset, end.location)];
            str = [str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        }
    }
    return str;
}




/**
 *  显示闪屏
 */
- (void)showSplashImgView
{
    WEAK_SELF;
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.splashImageView showSplashToView:[UIApplication sharedApplication].keyWindow];
    });
}

/**
 *  显示浮窗
 */
- (void)showFloat {
    if ([PywPlatformMain sharedPlatformMain].initialized == NO) {
        return;
    }
    
    if ([PywAppInfo sharedAppInfo].is_float) { // 初始化返回，是否显示悬浮窗
        [[UIApplication sharedApplication].keyWindow.rootViewController.view addSubview:[PywFloatView shareObject]];
    }
    
}
/**
 *  隐藏浮窗
 */
- (void)hideFloat {
    if ([PywPlatformMain sharedPlatformMain].initialized == NO) {
        return;
    }
    [[PywFloatView shareObject] removeFromSuperview];
}

/**
 获取SDK版本信息
 */
- (NSString *)getSdkVersion
{
    return [NSString stringWithFormat:@"SDK版本：%@",[PywAppInfo sharedAppInfo].verID];
}

#pragma  mark - 统一Appearance属性设置
/**
 *  各种Appearance属性设置
 */
- (void)configreAppearance{
    IQKeyboardManager *iqmanager = [IQKeyboardManager sharedManager];
    iqmanager.enable = NO;
    iqmanager.shouldResignOnTouchOutside = YES;
    iqmanager.shouldToolbarUsesTextFieldTintColor = YES;
    iqmanager.enableAutoToolbar = NO;
    
    PLog(@"%@",NSStringFromCGRect([UIApplication sharedApplication].statusBarFrame));
    UINavigationBar *navBar = [UINavigationBar appearance];
    //如果系统版本小于iOS7.0
    if (!iOS7) {
        // 设置导航栏背景图片
        [navBar setBackgroundImage:[UIImage imageWithName:@"navigationbar"] forBarMetrics:UIBarMetricsDefault];
        [navBar setBackgroundColor:[UIColor whiteColor]];
    }
    
    NSMutableDictionary *md = [NSMutableDictionary dictionary];
    // 导航栏标题颜色
    md[UITextAttributeTextColor] = [UIColor blackColor];
    // 字体
    md[UITextAttributeFont] = PywFont18;
    [navBar setTitleTextAttributes:md];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
